<template>
  <div class="container">
    <div class="header">
      <h1>周刊管理</h1>
      <div class="actions">
        <el-button type="primary" @click="addWeekly">添加周刊</el-button>
      </div>
    </div>
    
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="周刊标题">
          <el-input v-model="searchForm.title" placeholder="请输入周刊标题" clearable />
        </el-form-item>
        <el-form-item label="点赞数范围">
          <el-input-number v-model="searchForm.minLikes" :min="0" placeholder="最小值" />
          <span class="range-separator">-</span>
          <el-input-number v-model="searchForm.maxLikes" :min="0" placeholder="最大值" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <el-table :data="weeklyList" style="width: 100%" v-loading="loading">
        <el-table-column type="index" prop="id" label="ID" width="80" />
        <el-table-column prop="weekly_title" label="标题" />
        <el-table-column prop="weeklt_description" label="描述" :show-overflow-tooltip="true" />
        <el-table-column prop="like_numbers" label="点赞数" width="100" />
        <el-table-column label="文件" width="120">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="previewFile(scope.row)" 
              :disabled="!scope.row.file_url">
              查看文件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="150" />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="editWeekly(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteWeekly(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="周刊预览" fullscreen>
      <iframe :src="previewUrl" style="width: 100%; height: 90vh; border: none;"></iframe>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWeeklyPage, deleteWeekly as deleteWeeklyApi } from '@/api/weekly'
import { formatDateTime } from '@/utils/dateUtil'

const router = useRouter()
const loading = ref(false)
const weeklyList = ref([])
const previewVisible = ref(false)
const previewUrl = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单数据
const searchForm = reactive({
  title: '',
  minLikes: null,
  maxLikes: null
})

// 添加周刊
const addWeekly = () => {
  router.push('/weekly/add')
}

// 预览文件
const previewFile = (row) => {
  if (row.file_url) {
    previewUrl.value = row.file_url
    previewVisible.value = true
  } else {
    ElMessage.warning('该周刊没有关联文件')
  }
}

// 编辑周刊
const editWeekly = (row) => {
  router.push(`/weekly/edit/${row.id}`)
}

// 删除周刊
const deleteWeekly = (row) => {
  ElMessageBox.confirm(
    `确定要删除周刊"${row.weekly_title}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        console.log('Deleting weekly with ID:', row.id)
        const response = await deleteWeeklyApi(row.id)
        console.log('Delete response:', response)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          fetchData()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('Delete error:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.minLikes = null
  searchForm.maxLikes = null
  currentPage.value = 1
  fetchData()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchData()
}

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

const fetchData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件
    if (searchForm.title) {
      params.title = searchForm.title
    }
    
    if (searchForm.minLikes !== null) {
      params.minLikes = searchForm.minLikes
    }
    
    if (searchForm.maxLikes !== null) {
      params.maxLikes = searchForm.maxLikes
    }
    
    const response = await getWeeklyPage(
      params.pageNum, 
      params.pageSize, 
      params.title, 
      params.minLikes, 
      params.maxLikes
    )
    
    if (response.code === 200 && response.data) {
      // 处理分页数据
      if (response.data.records) {
        // 标准的MyBatis-Plus IPage返回格式
        weeklyList.value = response.data.records.map(formatWeeklyData)
        total.value = response.data.total || 0
      } else {
        // 处理可能的其他返回格式
        weeklyList.value = Array.isArray(response.data) 
          ? response.data.map(formatWeeklyData)
          : [formatWeeklyData(response.data)]
        total.value = weeklyList.value.length
      }
    } else {
      ElMessage.error(response.message || '获取周刊数据失败')
    }
  } catch (error) {
    console.error('获取周刊数据失败', error)
    ElMessage.error('获取周刊数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化周刊数据，处理不同命名格式
const formatWeeklyData = (item) => {
  // 格式化创建时间为中国日期格式（年月日）
  const rawDate = item.create_time || item.createTime || '';
  const formattedDate = rawDate ? formatDateTime(rawDate, 'YYYY年MM月DD日') : '';
  
  return {
    id: item.id,
    weekly_title: item.weekly_title || item.weeklyTitle || '',
    weeklt_description: item.weeklt_description || item.weekltDescription || '',
    like_numbers: item.like_numbers || item.likeNumbers || 0,
    file_url: item.file_url || item.fileUrl || '',
    delete_flag: item.delete_flag || item.deleteFlag || 0,
    create_time: formattedDate,
    update_time: item.update_time || item.updateTime || ''
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      
      .range-separator {
        margin: 0 5px;
      }
    }
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>